package org.jfbmonitor.connection;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

import javax.swing.JOptionPane;

import org.jfbmonitor.language.Language;

public class FBConnection {
	private Connection connection;
	private String url;
	private String classname;
	private String password;
	private String username;
	private static FBConnection sing;

	public FBConnection()  {
		Properties properties = new Properties();	
		/*InputStream is = this.getClass().getResourceAsStream(
				"connection.properties");*/
		InputStream is = null;
		File file = new File("");		
		String path = file.getAbsolutePath()+"\\";
		try {			
			is = new FileInputStream((new File(path+"connection.properties")));			
		} catch (FileNotFoundException e1) {			
			JOptionPane.showMessageDialog(null, e1.getMessage(),Language.getInstance().getProperties("OPTIONPANE.TITLE.ERROR"),JOptionPane.ERROR_MESSAGE);
		} 		
		try {
			properties.load(is);
			this.url = properties.getProperty("url");
			this.classname = properties.getProperty("classname");
			this.password = properties.getProperty("password");
			this.username = properties.getProperty("username");
			is.close();			
		} catch (IOException ioe) {
			JOptionPane.showMessageDialog(null, ioe.getMessage(),Language.getInstance().getProperties("OPTIONPANE.TITLE.ERROR"),JOptionPane.ERROR_MESSAGE);			
		}		
		try {
			Class.forName(this.classname);
		} catch (ClassNotFoundException e) {			
			JOptionPane.showMessageDialog(null, e.getMessage(),Language.getInstance().getProperties("OPTIONPANE.TITLE.ERROR"),JOptionPane.ERROR_MESSAGE);			
		}		
		try {
			connection = DriverManager.getConnection(this.url, this.username, this.password);
			connection.setAutoCommit(true);
		} catch (SQLException e) {
			JOptionPane.showMessageDialog(null, e.getMessage(),Language.getInstance().getProperties("OPTIONPANE.TITLE.ERROR"),JOptionPane.ERROR_MESSAGE); 
		}
	}

	public Connection getConnection() throws SQLException {		
		return this.connection;
	}

	public void closeConnection() throws SQLException {
		this.connection.close();
	}

	public static FBConnection getInstance() throws SQLException {
		if (sing == null) {
			sing = new FBConnection();
		}
		return sing;
	}
}
